package yy.zn.entity;

import io.swagger.annotations.ApiModelProperty;

import java.util.List;

/**
 * 通用的返回各种类型分页结果的信息类
 *
 * @param <Tp> 任意类型
 * @author WMT
 */
public class JsonPage<Tp> {

    // 定义需要的分页信息
    @ApiModelProperty(value = "总页数", name = "totalPages")
    private int totalPages;

    /**
     * 默认不超过 Integer.max
     */
    @ApiModelProperty(value = "总条数", name = "totalCount")
    private int totalCount;

    @ApiModelProperty(value = "当前页码", name = "page")
    private int page = 0;

    @ApiModelProperty(value = "每页条数", name = "pageSize")
    private int pageSize = 10;
    // 如果需要再添加其它属性即可

    // 除了分页信息,还有查询出的分页数据
    @ApiModelProperty(value = "分页数据", name = "list")
    private List<Tp> list;

    /**
     * @param <T>
     * @param page       从 1开始，第几页
     * @param pageSize   每页条数
     * @param totalCount 总记录数
     * @param list       本次查询的记录
     * @return
     */
    public static <T> JsonPage<T> builder(int page, int pageSize, int totalCount, List<T> list) {
        JsonPage<T> result = new JsonPage<>();
        // 赋值分页信息
        result.setTotalCount(totalCount);
        result.setPage(page);
        result.setPageSize(pageSize);

        result.setTotalPages(totalPages(pageSize, totalCount));
        // 赋值分页数据
        result.setList(list);
        return result;
    }

    private static int totalPages(int pageSize, int totalCount) {
        int rem = totalCount % pageSize;
        int div = totalCount / pageSize;
        if (rem == 0) {
            return div;
        }
        return div + 1;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public List<Tp> getList() {
        return list;
    }

    public void setList(List<Tp> list) {
        this.list = list;
    }
}
